import G2 from '@antv/g2'
import { thousandBitSeparator } from '../utils'

export default {
  methods: {
    thousandBitSeparator,
    drawPie (chart, data, dom, type, value, colors) {
      const self = this
      if (chart) {
        chart.destroy()
      }
      chart = new G2.Chart({
        container: dom,
        forceFit: true,
        height: this.height ? this.height : 500,
        padding: [80, 50, 50, 50],
        renderer: 'svg'
      })
      chart.source(data)
      chart.legend(false)
      chart.coord('theta')
      chart.tooltip({
        showTitle: false
      })
      if (colors) {
        chart.intervalStack().position('percent').color(type, colors).label(type, {
          formatter: function formatter (text, item) {
            const d = item.point
            return d[type] + ':' + (d.percent * 100).toFixed(2) + '%'
          },
          textStyle: {
            textAlign: 'middle', // 文本对齐方向，可取值为： start middle end
            fill: '#404040', // 文本的颜色
            fontSize: 11, // 文本大小
            fontWeight: 'bold', // 文本粗细
            textBaseline: 'middle' // 文本基准线，可取 top middle bottom，默认为middle
          },
          offset: 30,
          labelLine: {
            lineWidth: 1 // 线的粗细
          }
        }).tooltip(`${type}*percent*${value}`, function (type, percent, value) {
          percent = (percent * 100).toFixed(2) + '%'
          return {
            name: type,
            value: self.thousandBitSeparator(value) + ' (' + percent + ')'
          }
        }).style({
          lineWidth: 1,
          stroke: '#fff'
        })
      } else {
        chart.intervalStack().position('percent').color(type).label(type, function () {
          return {
            formatter: function formatter (text, item) {
              const d = item.point
              return d[type] + ':' + (d.percent * 100).toFixed(2) + '%'
            }
          }
        }).tooltip(`${type}*percent*${value}`, function (type, percent, value) {
          percent = (percent * 100).toFixed(2) + '%'
          return {
            name: type,
            value: self.thousandBitSeparator(value) + ' (' + percent + ')'
          }
        }).style({
          lineWidth: 1,
          stroke: '#fff'
        })
      }
      chart.render()
      return chart
    }
  }
}
